import React,{ Component } from 'react';
import {
	StyleSheet,
	View,
	Text,
	Image,
	FlatList,
	Button,
	TouchableOpacity,
	TouchableHighlight,
	Alert,
	Modal,
	TouchableWithoutFeedback,
	Dimensions,
	Animated,
    Easing
} from 'react-native';
import Picker from 'react-native-picker';
import Axios from '../../axios';
import StorageUtil from '../../common/storageUtil';
import NavigationService from '../../common/NavigationService';
import SwipeableFlatList from '../../common/FixSwipeadFlatList';
import NoDataPage,{NOCOLLECT} from '../../common/NoDataPage';
//import MonthPicker from '../../common/MonthPicker';
import SelectLink from '../../common/SelectLink';

const screenWidth= Dimensions.get('window').width;
const screenHeight= Dimensions.get('window').height;

class HeaderLeft extends Component{
	render(){
		return(
			<TouchableOpacity
				onPress = {()=>this.props.sideBarShow()}
			>
				<View style={styles.topLeftWraper}>
					<Image
						style={styles.topLeftImg}
						source={require('../../assets/images/person_icon.png')}
					/>
				</View>
			</TouchableOpacity>
		)
	}
}

class ReportCell extends Component{
	gotoDetail = (item)=>{
		NavigationService.navigate('ReportDetail',{
			id:item.MENU_ID,
			name:item.name
		})
	}

	render(){
		return (
			<View style={styles.reportCellWrap}>
				<TouchableOpacity
					onPress={()=>this.gotoDetail(this.props.item)}
				>
		    	<View style={styles.reportHeaderWrap}>
		    		<View style={styles.reportHeaderTitle}>
		    			<Image
							style={styles.reportHeaderImg}
		    				source={require('../../assets/images/daily_report.png')} />
		    			<Text style={styles.reportHeaderTxt}>{this.props.item.MENU_TITLE}({this.props.item.DATE})</Text>
		    		</View>
		    		<Image
		    			style={styles.reportHeaderRightIcon}
		    			source={require('../../assets/images/arrow_right.png')} />
		    	</View>
		    	<View style={styles.reportCellContentWrap}>
						<Text style={styles.reportContentTopTxt}>{this.props.item.TOTAL_TITLE}</Text>
		    		<Text style={styles.reportContentTotal}>{this.props.item.TOTAL}<Text style={styles.reportContentUnit}>{this.props.item.TOTAL_UNIT}</Text></Text>
		    		<View style={styles.reportContentBottomWrap}>
		    			<Text style={styles.reportContentBottomTxt}>{this.props.item.DETAIL1}</Text>
		    			<Text style={styles.reportContentBottomTxt}>{this.props.item.DETAIL2}</Text>
		    		</View>
		    	</View>
				</TouchableOpacity>
	    </View>
		)
	}
}

export default class Collection extends Component{
	constructor(props){
		super(props)
		this.sideBarWidth = screenWidth/5*3;
		this.sideBarMarginAnimate = new Animated.Value(-this.sideBarWidth);
		this.getUserInfo();
	}

	state = {
		reportList:[],
		isRefresh:true,
		isVisible: false, //我的气泡弹窗的
		buttonRect: {},
		isEmpty:false,
		sideBarShow:false,
		userInfo:"",
		selectLinkData:[{
			name:'收入降收',
			children:[{
				name:'显性',
				children:[{
					name:'用户流失',
					children:[{
						name:'用户质量问题'
					},{
						name:'正常用户发生行为问题'
					},{
						name:'其他'
					}]
				},{
					name:'在网用户降收',
					children:[{
						name:'产品结构变化'
					},{
						name:'用户使用费变化'
					},{
						name:'账务变化'
					},{
						name:'其他'
					}]
				}]
			},{
				name:'隐性'
			}]
		}]
	}

	static navigationOptions = ({navigation,navigationOptions})=>{
		return {
			title:"我的",
			headerStyle:{
				...navigationOptions.headerStyle,
				backgroundColor:"#f54545"

			},
			headerTitleStyle:{
				fontSize:18,
				flex:1,
				textAlign:'center'
			},
			headerLeft:<HeaderLeft sideBarShow = {navigation.getParam("sideBarShow")} />,
			headerRight:<View></View>
		}
	}

	getReportList = ()=>{
		StorageUtil.getItem(global.Constants.USER_COLLECT, []).then((arr)=>{

			Axios.ajax({
				url:'/app/getCollectMenu',
				data:{
					menuIds:arr
				}
			}).then((res)=>{
				let collectArr = new Array();
				for(let a of res.data){
					collectArr.push(a.MENU_ID);
				}
				StorageUtil.setItem(global.Constants.USER_COLLECT, collectArr);

				if( res.data.length==0 ){
					this.setState({isEmpty:true});
				}else{
					this.setState({isEmpty:false});
				}
				this.setState({reportList:res.data, isRefresh:false})
			});

		});
	}

	unCollect = (item)=>{
		this._flatListRef._onClose();
		let menuId = item.item.MENU_ID;

		StorageUtil.getItem(global.Constants.USER_COLLECT, []).then((arr)=>{
			console.log("collect before :"+JSON.stringify(arr));
			if( Array.isArray(arr)==false ){
				return;
			}
			let pos = arr.indexOf(menuId);
			if( pos!=-1 ){
				arr.splice(pos, 1);
			}
			console.log("collect after :"+JSON.stringify(arr));
			StorageUtil.setItem("USER_COLLECT", arr);

			this.onRefresh();
		});

		console.log("menu item:"+JSON.stringify(item));
		console.log("menu item:"+item.item.MENU_ID);
	}

	componentDidMount(){
		//this.getReportList();
		this.subs = [this.props.navigation.addListener('didFocus', () => this.getReportList()),];
		this.props.navigation.setParams({sideBarShow:this.sideBarShow});
		//this.MonthPicker.show();
	}

	componentWillUnmount() {
		this.subs.forEach(sub => sub.remove());
		this.props.navigation.setParams({sideBarShow:this.sideBarShow});
	}

	onRefresh = ()=>{
		this.getReportList();
	}

	_footer = () => {
	  return <Text style={[styles.txt]}>这是底线</Text>;
	}

	getUserInfo = ()=>{

		StorageUtil.getItem(global.Constants.USER_INFO).then((userInfo)=>{
			if( userInfo ){
				this.setState({userInfo:userInfo.staffName+"("+userInfo.staffNo+")"});
			}
		});
	}

	sideBarShow = ()=>{
		this.setState({sideBarShow:true})
  		Animated.timing(
	        this.sideBarMarginAnimate,
	        {
	            toValue: 0,
	            duration: 300,
	            easing: Easing.easeInEaseOut
	        }
        ).start()
    }

	sideBarHide = ()=>{
  		Animated.timing(
	        this.sideBarMarginAnimate,
	        {
	            toValue: -this.sideBarWidth,
	            duration: 300,
	            easing: Easing.easeInEaseOut
	        }
	    ).start(()=>{
	      	this.setState({sideBarShow:false})
	    })
	}

	getQuickActions=(item)=>{
	    return (
				<View style={styles.quickAContent}>
	        <TouchableOpacity
						onPress={()=>Alert.alert('取消收藏','确认取消收藏?',
						  [
						    {text:"取消", onPress:()=>this._flatListRef._onClose()},
						    {text:"确认", onPress:()=>this.unCollect(item)}
						  ]
						)}
	        >
		        <View style={styles.quick}>
		            <Text style={styles.delete}>取消收藏</Text>
		        </View>
	        </TouchableOpacity>
	      </View>
			)
	};

	quit = ()=>{
		StorageUtil.removeItem(global.Constants.UESR_TOKEN);
		NavigationService.navigate('Auth');
	}

	selectShow = ()=>{
		this.setState({isVisible:true})
	}

	render(){
		return(
			<View style={styles.container}>
				<SwipeableFlatList
					data={this.state.reportList}
				 	keyExtractor={(item)=>item.MENU_ID.toString()}
				    renderItem={({item}) => (<ReportCell item={item} />)}
					ref={ref => {
					    this._flatListRef = ref;
					}}
				    onRefresh={() => this.onRefresh()}
	  				refreshing={this.state.isRefresh}
					//ListFooterComponent={this._footer}
					bounceFirstRowOnMount={false}//进去的时候不展示侧滑效果
	  				renderQuickActions={(item)=>this.getQuickActions(item)}//创建侧滑菜单
            		maxSwipeDistance={100}//可展开（滑动）的距离
					ListEmptyComponent={<NoDataPage text="暂无收藏" imageSource={NOCOLLECT}/>}
				/>
				<Modal
					animationType='none'            // 淡入淡出
				    transparent={true}              // 透明
				    visible={this.state.sideBarShow}    // 根据isModal决定是否显示
				    onRequestClose={() => this.sideBarHide()} //android必须实现,android返回键执行
				>
					<View style={{flex:1,flexDirection:'row'}}>
						<Animated.View style={{width: this.sideBarWidth,marginLeft:this.sideBarMarginAnimate, height: screenHeight, backgroundColor: '#fff',}}>
							<View style={styles.sideBarLogoWrap}>
				            	<Image
			              			style={styles.sideBarLogo}
									source={require('../../assets/images/logo.png')}
		              			/>
								<Text style={{color:'#757575'}}>{this.state.userInfo}</Text>
			            	</View>
				            <View>
				            	<TouchableOpacity
									style={styles.sideBarWrap}
									activeOpacity={0.5}
									onPress={()=>Alert.alert('退出','是否确认退出?',
										[
										    {text:"取消"},
										    {text:"确认", onPress:()=>this.quit()}
										]
									)}
			               		>
										<View style={styles.sideBarLine}>
							                <Image
							               		style={styles.sideBarIcon}
												source={require("../../assets/images/exit.png")}
				               				/>
					               			<Text style={styles.sideBarTxt}>退出登录</Text>
										</View>
			           			</TouchableOpacity>
			            	</View>
							<View style={styles.version}>
								<Text style={styles.versionTxt}>v0.0.1</Text>
							</View>
						</Animated.View>
						<TouchableOpacity style={{opacity:0.5,width:screenWidth,height:screenHeight,backgroundColor:'#333'}}
						 	onPress={()=>{
								this.sideBarHide();
							}}
							activeOpacity={0.5}
	           			/>
					</View>
				</Modal>
				{
					// <Button 
					// 	title="aaa"
					// 	onPress={()=>this.MonthPicker.show()}
					// />
				}
				{
					// <MonthPicker 
					// 	curDate={'2018-11'}
					// 	minDate={'2017-08'}
					// 	maxDate={'2019-03'}
					// 	ref={picker=>this.MonthPicker = picker}
					// 	onPickerConfirm={(data)=>{
					// 		console.log(data)
					// 	}}
					// />
				}

				{
					// <Button 
					// 	title="fuxuan"
					// 	onPress={()=>{
					// 		this.selectShow()
					// 	}}
					// />
					// <SelectLink 
					// 	visible={this.state.isVisible}
					// 	sourceData={this.state.selectLinkData}
					// 	onSubmit={(data)=>{
					// 		console.log(data)
					// 	}}
					// />
				}
			</View>
		)
	}

}

const styles = StyleSheet.create({
	version:{
		position:'absolute',
		bottom:10,
		left:'50%',
		marginLeft:-20
	},
	versionTxt:{
		textAlign:'center',
		color:'#757575',
		fontSize:14
	},
	sideBarLine:{
		borderTopWidth:1,
		borderTopColor:"#f7f7f7",
		flexDirection:'row',
		alignItems:'center',
		height:50
	},
	sideBarWrap:{
		paddingLeft:20,
		paddingRight:20
	},
	sideBarTxt:{
		color:'#757575',
		fontSize:16,
		marginLeft:10
	},
	sideBarIcon:{
		width:22,
		height:22
	},
	sideBarLogoWrap:{
		height:140,
		justifyContent:'center',
		alignItems:'center'
	},
	sideBarLogo:{
		width:80,
		height:80
	},
	//侧滑菜单的样式
	quickAContent:{
        flex:1,
        flexDirection:'row',
        justifyContent:'flex-end'
    },
    quick:{
        backgroundColor:"#f54545",
        flex:1,
        alignItems:'center',//水平靠右
        justifyContent:'center',//上下居中
        width:100,
        marginTop:10
	},
	delete:{
	    color:"#fff",
	    fontSize:18
	},
	container : {
		flex : 1,
		backgroundColor:'#f5f5f5'
	},
	textColor:{
		color:'#f00'
	},
	topLeftWraper:{
		flex:1,
		flexDirection:'row',
		justifyContent:'center',
		alignItems:'center'
	},
	topLeftImg:{
		width:22,
		height:22,
		marginLeft:10
	},
	topLeftTxt:{
		color:'#fff',
		fontSize:16,
		marginLeft:5
	},
	topRightImg:{
		width:22,
		height:22,
		marginRight:10
	},
	reportCellWrap:{
		backgroundColor:"#fff",
		marginTop:10
	},
	reportHeaderWrap:{
		flex:1,
		flexDirection:'row',
		alignItems:"center",
		padding:10,
		borderBottomWidth:1,
		borderBottomColor:"#f7f7f7"
	},
	reportHeaderTitle:{
		flex:1,
		flexDirection:'row',
		alignItems:"center"
	},
	reportHeaderImg:{
		width:16,
		height:18,
		marginRight:5
	},
	reportHeaderTxt:{
		fontSize:14
	},
	reportHeaderRightIcon:{
		width:16,
		height:18
	},
	reportCellContentWrap:{
		flex:1,
		justifyContent:"center",
		marginTop:20,
		marginBottom:20
	},
	reportContentTopTxt:{
		textAlign:"center",
		fontSize:14
	},
	reportContentTotal:{
		textAlign:"center",
		fontSize:26,
		color:"#f54545",
		marginTop:10,
		marginBottom:10
	},
	reportContentUnit:{
		fontSize:12,
		fontWeight:"bold"
	},
	reportContentBottomWrap:{
		flex:1,
		flexDirection:"row",
		justifyContent:"center"
	},
	reportContentBottomTxt:{
		fontSize:14,
		marginRight:10,
		marginLeft:10
	},
	txt: {
	    textAlign: 'center',
	    textAlignVertical: 'center',
	    //color: 'white',
	    fontSize: 10,
	}
})
